<template>
  <div ref="messageList" class="chat-messages" @scroll="handleScroll">
    <div v-if="loading" class="loading-container">
      <el-loading size="small" />
      <span class="loading-text">加载更多消息...</span>
    </div>
    <div v-else-if="!hasMore" class="no-more-messages">
      <span>没有更多消息了</span>
    </div>
    <div v-for="msg in localMessages" :key="msg.id" :class="['chat-message', getMessageClass(msg)]">
      <!-- 系统消息 -->
      <template v-if="msg.senderType === 'system'">
        <div class="system-message-wrapper">
          <div v-if="msg.sendTime" class="message-time system-time">
            {{ formatMessageTime(msg.sendTime) }}
          </div>
          <div class="message-content message-system">
            {{ msg.content }}
          </div>
        </div>
      </template>

      <!-- 普通消息 -->
      <template v-else>
        <div class="avatar-wrapper">
          <img
            v-if="msg.senderType === 'agent'"
            :src="props.currentContact.agentAvatar || defaultAvatar"
            class="avatar"
          />
          <img v-else :src="msg.avatar || defaultAvatar" class="avatar" />
        </div>
        <div class="message-wrapper">
          <div class="message-header">
            <div v-if="msg.senderName" class="sender-name">
              {{ msg.senderName }}
            </div>
            <div v-else-if="msg.senderType === 'agent'" class="sender-name">客服</div>
            <div v-else-if="msg.senderType === 'customer'" class="sender-name">
              {{ props.currentContact?.name || "客户" }}
            </div>
            <div v-if="msg.sendTime" class="message-time">
              {{ formatMessageTime(msg.sendTime) }}
            </div>
          </div>
          <div :class="['message-content', `message-${msg.senderType || 'customer'}`]">
            <!-- 文本消息 -->
            <template v-if="msg.type === 'text'">
              {{ msg.content }}
            </template>

            <!-- 文件消息 -->
            <template v-else-if="msg.type === 'file'">
              <FileMessage
                :file-url="msg.content"
                :file-name="msg.fileName"
                :file-size="msg.fileSize"
              />
            </template>

            <!-- 其他类型消息 -->
            <template v-else>
              {{ msg.content }}
            </template>
          </div>
          <!-- 添加已读状态显示 -->
          <div v-if="msg.senderType === 'agent'" class="message-status">
            <span v-if="msg.hasRead === 1" class="read-status">已读</span>
            <span v-else class="un-read-status">未读</span>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script setup>
import { defineProps, defineEmits, watch, ref, onMounted, nextTick, computed } from "vue";
import { formatTime } from "@/utils/date";
import defaultAvatar from "@/assets/icons/header-icon.png";
import ChatAPI from "@/api/chat.api";
import FileMessage from "./FileMessage.vue";

const props = defineProps({
  messages: Array,
  sessionId: [String, Number],
  currentContact: Object,
});

const emit = defineEmits(["update:messages"]);

const messageList = ref(null);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const hasMore = ref(true);
const isFirstLoad = ref(true);

// 使用计算属性直接使用props.messages，不再维护本地状态
const localMessages = computed(() => props.messages || []);

// 获取会话历史记录
async function fetchChatHistory(page = 1, append = false) {
  if (!props.sessionId || loading.value) return;
  const seeionId = props.sessionId;
  try {
    loading.value = true;
    console.log(`加载历史消息: 页码=${page}, 追加=${append}`);

    const res = await ChatAPI.getChatHistory({
      sessionId: props.sessionId,
      pageNum: page,
      pageSize: pageSize.value,
    });

    const historyMessages = res.list || [];
    historyMessages.reverse();

    // 判断是否还有更多消息
    hasMore.value = historyMessages.length === pageSize.value;
    console.log(`是否有更多消息: ${hasMore.value}, 获取到消息数: ${historyMessages.length}`);

    // 转换消息格式
    const formattedMessages = historyMessages.map((msg) => ({
      id: msg.id || `hist_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
      fromMe: msg.senderType === "agent",
      avatar: msg.senderType === "agent" ? "" : props.currentContact?.avatar || "",
      type: msg.type || "text",
      hasRead: msg.hasRead || 0,
      content: msg.content,
      senderType: msg.senderType,
      senderName:
        msg.senderType === "agent"
          ? msg.senderName || "客服"
          : props.currentContact?.name || "客户",
      sendTime: msg.sendTime,
    }));

    if (append) {
      // 保存当前滚动位置
      const oldScrollHeight = messageList.value.scrollHeight;
      const oldScrollTop = messageList.value.scrollTop;

      // 将新消息添加到顶部并通知父组件更新
      const newMessages = [...formattedMessages, ...props.messages];
      console.log(
        `追加历史消息: 新消息数=${formattedMessages.length}, 总消息数=${newMessages.length}`
      );
      emit("update:messages", newMessages, seeionId);

      // 更新当前页码
      currentPage.value = page;

      // 在下一个渲染周期后恢复滚动位置
      nextTick(() => {
        if (messageList.value) {
          const newScrollHeight = messageList.value.scrollHeight;
          const scrollDiff = newScrollHeight - oldScrollHeight;
          messageList.value.scrollTop = oldScrollTop + scrollDiff;
          console.log(
            `调整滚动位置: 旧=${oldScrollTop}, 差值=${scrollDiff}, 新=${oldScrollTop + scrollDiff}`
          );
        }
      });
    } else {
      // 第一次加载或刷新，直接替换消息列表
      console.log(`首次加载消息: 消息数=${formattedMessages.length}`);
      emit("update:messages", formattedMessages, seeionId);
      currentPage.value = 1;

      // 只有首次加载第一页时才自动滚动到底部
      if (isFirstLoad.value && page === 1) {
        scrollToBottom();
        isFirstLoad.value = false;
      }
    }
  } catch (error) {
    console.error("获取会话历史记录失败", error);
    // 如果获取失败，使用空数组
    if (!append) {
      emit("update:messages", [], seeionId);
    }
  } finally {
    loading.value = false;
  }
}

// 处理滚动事件
function handleScroll() {
  if (!messageList.value) return;

  const { scrollTop } = messageList.value;

  // 如果滚动到顶部且还有更多消息，加载更多
  if (scrollTop < 20 && hasMore.value && !loading.value) {
    console.log(
      `检测到滚动到顶部: scrollTop=${scrollTop}, 当前页=${currentPage.value}, 加载更多消息`
    );
    fetchChatHistory(currentPage.value + 1, true);
  }
}

// 检查是否滚动到底部
function isScrolledToBottom() {
  if (!messageList.value) return true;

  const { scrollTop, scrollHeight, clientHeight } = messageList.value;
  // 如果滚动位置在底部附近（允许10px的误差），则认为是在底部
  return scrollHeight - scrollTop - clientHeight < 10;
}

// 滚动到底部
function scrollToBottom() {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  });
}

// 暴露方法给父组件
defineExpose({
  scrollToBottom,
});

// 监听sessionId变化，重新加载消息
watch(
  () => props.sessionId,
  (newVal) => {
    if (newVal) {
      isFirstLoad.value = true;
      currentPage.value = 1;
      hasMore.value = true;
      fetchChatHistory(1, false);
    }
  }
);

// 监听messages变化，自动滚动到底部
watch(
  () => props.messages,
  (newMessages, oldMessages) => {
    if (newMessages && oldMessages && newMessages.length > oldMessages.length) {
      // 如果消息数量增加了，检查是否需要滚动到底部
      const shouldScrollToBottom = isScrolledToBottom();
      if (shouldScrollToBottom) {
        scrollToBottom();
      }
    }
  },
  { deep: true }
);

// 组件挂载后加载消息
onMounted(() => {
  if (props.sessionId) {
    fetchChatHistory(1, false);
  } else if (props.messages && props.messages.length > 0) {
    scrollToBottom();
  }
});

function getMessageClass(msg) {
  if (msg.senderType === "system") return "system-message";
  return msg.fromMe ? "from-me" : "from-other";
}

function formatMessageTime(timestamp) {
  return formatTime(timestamp);
}
</script>
<style scoped>
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}
.chat-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
}
.chat-message.from-me {
  flex-direction: row-reverse;
}
.chat-message.from-me .avatar-wrapper {
  align-items: flex-start;
}
.chat-message.system-message {
  justify-content: center;
  width: 100%;
}
.system-message-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}
.system-time {
  margin-bottom: 2px;
  text-align: center;
}
.avatar-wrapper {
  height: 100%;
  display: flex;
  align-items: flex-start;
  padding-top: 4px;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 8px;
}
.message-wrapper {
  display: flex;
  flex-direction: column;
  max-width: 60%;
}
.message-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 2px;
  width: 100%;
}
.sender-name {
  font-size: 12px;
  font-weight: 500;
  color: #666;
  margin-right: 8px;
}
.message-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}
.from-me .message-wrapper .message-time {
  text-align: right;
}
.message-content {
  background: #fff;
  border-radius: 6px;
  padding: 8px 14px;
  word-break: break-all;
}
.message-system {
  background: #f0f0f0;
  color: #666;
  font-style: italic;
  padding: 4px 10px;
  font-size: 12px;
  border-radius: 10px;
  max-width: 80%;
  width: auto;
  display: inline-block;
  text-align: center;
}
.message-agent {
  background: #e1f3ff;
}
.message-customer {
  background: #fff;
}
.file-message {
  display: flex;
  align-items: center;
  min-width: 220px;
}
.file-icon {
  font-size: 24px;
  margin-right: 10px;
  color: #409eff;
}
.file-info {
  flex: 1;
  min-width: 0;
}
.file-name {
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}
.file-size {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
.file-actions {
  margin-left: 10px;
}
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 4px;
  margin-bottom: 10px;
}
.loading-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
.no-more-messages {
  text-align: center;
  padding: 5px 0;
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}
.message-status {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  text-align: right;
}
.read-status {
  color: #378d0c;
}
.un-read-status {
  color: #909399;
}
</style>
